from django.db import models
from django.contrib.auth.models import AbstractUser
from django.utils import timezone


class UserRole:
    """用户角色枚举"""
    VISITOR = 0  # 访客（未登录）
    USER = 1     # 普通用户
    AUTHOR = 2   # 作者
    ADMIN = 3    # 管理员
    SUPER_ADMIN = 4  # 超级管理员（系统所有者）
    
    CHOICES = [
        (VISITOR, '访客'),
        (USER, '普通用户'),
        (AUTHOR, '作者'),
        (ADMIN, '管理员'),
        (SUPER_ADMIN, '超级管理员'),
    ]


class User(AbstractUser):
    """用户模型"""
    
    # 扩展字段
    display_name = models.CharField('显示名称', max_length=100, blank=True)
    bio = models.TextField('个人简介', blank=True)
    avatar_url = models.CharField('头像URL', max_length=255, blank=True)
    role = models.IntegerField('角色', choices=UserRole.CHOICES, default=UserRole.USER)
    is_active = models.BooleanField('是否激活', default=True)
    created_at = models.DateTimeField('创建时间', default=timezone.now)
    updated_at = models.DateTimeField('更新时间', auto_now=True)
    
    class Meta:
        db_table = 'blog_user'
        verbose_name = '用户'
        verbose_name_plural = '用户'
    
    def __str__(self):
        return self.username
    
    def save(self, *args, **kwargs):
        # 如果没有设置显示名称，使用用户名
        if not self.display_name:
            self.display_name = self.username
        super().save(*args, **kwargs)
    
    @property
    def is_author(self):
        """判断是否为作者"""
        return self.role >= UserRole.AUTHOR
    
    @property
    def is_admin(self):
        """判断是否为管理员"""
        return self.role >= UserRole.ADMIN
    
    @property
    def is_super_admin(self):
        """判断是否为超级管理员"""
        return self.role == UserRole.SUPER_ADMIN


class UserProfile(models.Model):
    """用户详细资料模型"""
    
    user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='profile')
    phone = models.CharField('手机号', max_length=20, blank=True)
    website = models.URLField('个人网站', blank=True)
    location = models.CharField('所在地', max_length=100, blank=True)
    company = models.CharField('公司', max_length=100, blank=True)
    job_title = models.CharField('职位', max_length=100, blank=True)
    github_url = models.URLField('GitHub', blank=True)
    twitter_url = models.URLField('Twitter', blank=True)
    linkedin_url = models.URLField('LinkedIn', blank=True)
    
    # 统计信息
    article_count = models.IntegerField('文章数量', default=0)
    comment_count = models.IntegerField('评论数量', default=0)
    like_count = models.IntegerField('获赞数量', default=0)
    view_count = models.IntegerField('被浏览次数', default=0)
    
    # 设置
    email_notifications = models.BooleanField('邮件通知', default=True)
    comment_notifications = models.BooleanField('评论通知', default=True)
    
    created_at = models.DateTimeField('创建时间', default=timezone.now)
    updated_at = models.DateTimeField('更新时间', auto_now=True)
    
    class Meta:
        db_table = 'blog_user_profile'
        verbose_name = '用户资料'
        verbose_name_plural = '用户资料'
    
    def __str__(self):
        return f"{self.user.username} 的资料"


class Permission(models.Model):
    """权限模型"""
    
    name = models.CharField('权限名称', max_length=50)
    code = models.CharField('权限代码', max_length=50, unique=True)
    description = models.TextField('权限描述', blank=True)
    category = models.CharField('权限分类', max_length=30)
    created_at = models.DateTimeField('创建时间', default=timezone.now)
    
    class Meta:
        db_table = 'blog_permission'
        verbose_name = '权限'
        verbose_name_plural = '权限'
    
    def __str__(self):
        return self.name


class RolePermission(models.Model):
    """角色权限关联模型"""
    
    role = models.IntegerField('角色ID', choices=UserRole.CHOICES)
    permission = models.ForeignKey(Permission, on_delete=models.CASCADE)
    created_at = models.DateTimeField('创建时间', default=timezone.now)
    
    class Meta:
        db_table = 'blog_role_permission'
        verbose_name = '角色权限'
        verbose_name_plural = '角色权限'
        unique_together = ['role', 'permission']
    
    def __str__(self):
        return f"{self.get_role_display()} - {self.permission.name}"


class ResourcePermission(models.Model):
    """资源权限模型"""
    
    RESOURCE_TYPES = [
        ('article', '文章'),
        ('category', '分类'),
        ('comment', '评论'),
        ('user', '用户'),
    ]
    
    PERMISSION_TYPES = [
        ('read', '读取'),
        ('write', '写入'),
        ('delete', '删除'),
        ('manage', '管理'),
    ]
    
    resource_type = models.CharField('资源类型', max_length=30, choices=RESOURCE_TYPES)
    resource_id = models.IntegerField('资源ID')
    permission_type = models.CharField('权限类型', max_length=30, choices=PERMISSION_TYPES)
    user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True)
    role = models.IntegerField('角色ID', choices=UserRole.CHOICES, null=True, blank=True)
    granted_by = models.ForeignKey(User, on_delete=models.CASCADE, related_name='granted_permissions')
    expires_at = models.DateTimeField('过期时间', null=True, blank=True)
    created_at = models.DateTimeField('创建时间', default=timezone.now)
    
    class Meta:
        db_table = 'blog_resource_permission'
        verbose_name = '资源权限'
        verbose_name_plural = '资源权限'
    
    def __str__(self):
        return f"{self.resource_type}.{self.resource_id} - {self.permission_type}"